package cn.edu.lzu.service.impl;

import cn.edu.lzu.common.assist.DataPage;
import cn.edu.lzu.common.assist.ResponseResult;
import cn.edu.lzu.common.util.Email;
import cn.edu.lzu.dao.*;
import cn.edu.lzu.entity.*;
import cn.edu.lzu.service.UserService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

/**
 * @PackageName: cn.edu.lzu.service.impl
 * @ClassName: UserServiceImpl
 * @Description: TODO 关于用户信息的逻辑操作
 * @Author: 张琦[QQ:3098086691]
 * @Date: 2020/2/25 23:23
 * @Version: 1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BookRegisteMapper bookRegisteMapper;
    @Resource
    private LiveHabitMapper liveHabitMapper;
    @Resource
    private PresentHealthConditionMapper presentHealthConditionMapper;
    @Resource
    private PastDiseaseHistoryMapper pastDiseaseHistoryMapper;
    @Resource
    private FamilyDiseaseHistoryMapper familyDiseaseHistoryMapper;

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 在book_registe表中添加挂号信息
     * @Date: 2020/2/27 16:08
     * @Param: [user, examiner, examinePackage, examineDate]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult hospitalSubmitUserMsg(User user, Examiner examiner, Integer examinePackage, Date examineDate) {
        //检查user表中是否已经注册了该用户的信息;如果没有，就先在user表中注册（添加一条记录，写入身份证号、姓名、邮箱、婚姻状况，密码信息——密码为出生年月，然后再在book_registe表中添加信息
        //如果已经在user表中注册过了，就直接在book_registe表中添加信息
        BookRegiste bookRegiste=new BookRegiste();
        bookRegiste.setBookDate(examineDate);
        bookRegiste.setDeleted(false);
        bookRegiste.setUserStatus(1);
        if(examiner!=null){
            bookRegiste.setExaminerId(examiner.getExaminerId());
        }else{
            bookRegiste.setExaminerId(0);
        }
        //bookRegiste.setExamineItemId();暂时忽略单独的体检项目的记录
        bookRegiste.setExaminePackageId(examinePackage);
        bookRegiste.setUserIdentity(user.getUserIdentity());

        User user1=userMapper.selUserByIdentity(user);

        int insBookRegisteResult;
        ResponseResult responseResult=new ResponseResult();

        //该用户在user表中已经存在并且没有被删除，那么在book_registe中搜索检查该用户是否在该单位处于挂号预约状态；如果是，则不能重复挂号；
        // 如果处于已完成状态或者在book_registe中还没有记录，则直接添加book_registe表
        if(user1!=null && user1.isDeleted()==false){
            if(bookRegisteMapper.selRegisteMsgRegisting(examiner, user)==null)
                insBookRegisteResult=bookRegisteMapper.insRegisteMsg(bookRegiste);
            else{
                responseResult.setCode(0);
                responseResult.setMsg("您的上次挂号还未检查完毕，不能重复挂号！");
                return responseResult;
            }
        }else if(user1!=null && user1.isDeleted()==true){
        //该用户在user表中已经存在但是被删除，将is_deleted置为0然后更新其余信息
            insBookRegisteResult=0;
        }else{
        //该用户在user表中还不存在，添加该条记录,然后再在book_registe中添加信息
            user.setPassword(user.getUserIdentity().substring(6, 12));
            int insUserResult=userMapper.insRegisteUser(user);
            if(insUserResult==1){
                insBookRegisteResult=bookRegisteMapper.insRegisteMsg(bookRegiste);
            }

            else
                insBookRegisteResult=0;
        }

        responseResult.setCode(insBookRegisteResult);
        if(insBookRegisteResult==1){
            int id=bookRegisteMapper.selByDateAndUserIdentity(examineDate, user.getUserIdentity());
            responseResult.setMsg("挂号信息写入成功！@"+"id="+id+"&bookDate="+examineDate);
        }

        else
            responseResult.setMsg("挂号信息写入失败！");

        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据身份证号获取未被删除的user
     * @Date: 2020/3/19 23:19
     * @Param: [userIdentity]
     * @Return: cn.edu.lzu.entity.User
     **/
    @Override
    public User getUserByUserIdentity(String userIdentity) {
        User user=userMapper.selUserByIdentityAndTrue(userIdentity);
        return user;
    }

    @Override
    public ResponseResult setUserHealthMsg(User user, LiveHabit liveHabit, PastDiseaseHistory pastDiseaseHistory, PresentHealthCondition presentHealthCondition, FamilyDiseaseHistory familyDiseaseHistory) {
        liveHabit.setRecordTime(new Timestamp(System.currentTimeMillis()));
        pastDiseaseHistory.setRecordTime(new Timestamp(System.currentTimeMillis()));
        presentHealthCondition.setRecordTime(new Timestamp(System.currentTimeMillis()));
        familyDiseaseHistory.setRecordTime(new Timestamp(System.currentTimeMillis()));
        ResponseResult responseResult=new ResponseResult();
        int result1=userMapper.updUserBaseMsg(user);
        if(result1==1){
            int result2=liveHabitMapper.insLiveHabitMsg(liveHabit);
            if(result2==1){
                int result3=pastDiseaseHistoryMapper.insPastDiseaseHistoryMsg(pastDiseaseHistory);
                if(result3==1){
                    int result4=presentHealthConditionMapper.insPresentHealthConditionMsg(presentHealthCondition);
                    if(result4==1){
                        int result5=familyDiseaseHistoryMapper.insFamilyDiseaseHistoryMsg(familyDiseaseHistory);
                        if(result5==1){
                            responseResult.setCode(1);
                            responseResult.setMsg("信息写入成功！");
                        }else{
                            responseResult.setCode(0);
                            responseResult.setMsg("信息写入失败！");
                        }
                    }else{
                        responseResult.setCode(0);
                        responseResult.setMsg("信息写入失败！");
                    }
                }else{
                    responseResult.setCode(0);
                    responseResult.setMsg("信息写入失败！");
                }
            }else{
                responseResult.setCode(0);
                responseResult.setMsg("信息写入失败！");
            }
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("信息写入失败！");
        }
        return responseResult;
    }

    @Override
    public ResponseResult sendEmail(String userIdentity, int id, Date bookDate) {
        User user=userMapper.selUserByIdentityAndTrue(userIdentity);
        String sex="";
        if(Integer.parseInt(userIdentity.substring(15, 16))%2==0){
            sex="女士";
        }else{
            sex="先生";
        }
        String msg=user.getUserName()+sex+"(身份证号："+userIdentity+")"+"您好，恭喜您挂号成功。预约日期为："+bookDate+"；体检编号为："+id+"。预祝您本次体检顺利！"+" 【滕飞健康】";
        ResponseResult responseResult=new ResponseResult();
        try {
            Email.sendEmail(user.getEmail(), "挂号通知", msg);
            responseResult.setCode(1);
        } catch (MessagingException e) {
            e.printStackTrace();
            responseResult.setCode(0);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            responseResult.setCode(0);
        }
        if (responseResult.getCode()==1){
            responseResult.setMsg("挂号信息已发送！");
        }else{
            responseResult.setMsg("挂号信息发送失败！");
        }
        return responseResult;
    }

    @Override
    public ResponseResult findPwd(String userName, String userIdentity, String eamil) {
        User user=userMapper.selUserByIdentityAndName(userName, userIdentity);
        ResponseResult responseResult=new ResponseResult();
        if(user==null){
            responseResult.setCode(0);
            responseResult.setMsg("没有该用户信息！");
        }else{
            try {
                Email.sendEmail(eamil, "找回密码", "您的密码为："+user.getPassword()+" 【滕飞健康】");
                responseResult.setCode(1);
                responseResult.setMsg("密码找回成功！");
            } catch (MessagingException e) {
                responseResult.setCode(0);
                responseResult.setMsg("密码找回失败！");
                e.printStackTrace();
            } catch (javax.mail.MessagingException e) {
                responseResult.setCode(0);
                responseResult.setMsg("密码找回失败！");
                e.printStackTrace();
            }
        }
        return responseResult;
    }


    @Override
    public ResponseResult bookSubmitUserMsg(User user,long unitId, Integer examinePackage, Date examineDate) {
        //检查user表中是否已经注册了该用户的信息;如果没有，就先在user表中注册（添加一条记录，写入身份证号、姓名、邮箱、婚姻状况，密码信息——密码为出生年月，然后再在book_registe表中添加信息
        //如果已经在user表中注册过了，就直接在book_registe表中添加信息
        BookRegiste bookRegiste=new BookRegiste();
        bookRegiste.setBookDate(examineDate);
        bookRegiste.setDeleted(false);
        bookRegiste.setUserStatus(1);
        bookRegiste.setExaminerId(0);

        //bookRegiste.setExamineItemId();暂时忽略单独的体检项目的记录
        bookRegiste.setExaminePackageId(examinePackage);
        bookRegiste.setUserIdentity(user.getUserIdentity());

        User user1=userMapper.selUserByIdentity(user);

        int insBookRegisteResult;
        ResponseResult responseResult=new ResponseResult();

        //该用户在user表中已经存在并且没有被删除，那么在book_registe中搜索检查该用户是否在该单位处于挂号预约状态；如果是，则不能重复挂号；
        // 如果处于已完成状态或者在book_registe中还没有记录，则直接添加book_registe表
        if(user1!=null && user1.isDeleted()==false){
            System.out.println("bookRegisteMapper.selRegisteMsgRegisted(unitId, user):"+bookRegisteMapper.selRegisteMsgRegisted(unitId, user));
            System.out.println("bookRegisteMapper.selBookedMsg(user)："+bookRegisteMapper.selBookedMsg(user, unitId));
            if((bookRegisteMapper.selRegisteMsgRegisted(unitId, user)==null ||(bookRegisteMapper.selRegisteMsgRegisted(unitId, user)).size()==0)&& (bookRegisteMapper.selBookedMsg(user, unitId)==null || (bookRegisteMapper.selBookedMsg(user, unitId)).size()==0)){
                insBookRegisteResult=bookRegisteMapper.insBookRegisteMsg(bookRegiste, unitId);
            }
            else{
                responseResult.setCode(0);
                responseResult.setMsg("您的上次挂号还未检查完毕，不能重复挂号！");
                return responseResult;
            }
        }else if(user1!=null && user1.isDeleted()==true){
            //该用户在user表中已经存在但是被删除，将is_deleted置为0然后更新其余信息
            insBookRegisteResult=0;
        }else{
            //该用户在user表中还不存在，添加该条记录,然后再在book_registe中添加信息
            user.setPassword(user.getUserIdentity().substring(6, 12));
            int insUserResult=userMapper.insRegisteUser(user);
            if(insUserResult==1){
                insBookRegisteResult=bookRegisteMapper.insRegisteMsg(bookRegiste);
            }

            else
                insBookRegisteResult=0;
        }

        responseResult.setCode(insBookRegisteResult);
        if(insBookRegisteResult==1){
            int id=bookRegisteMapper.selByDateAndUserIdentity(examineDate, user.getUserIdentity());
            responseResult.setMsg("挂号信息写入成功！@"+"id="+id+"&bookDate="+examineDate);
        }

        else
            responseResult.setMsg("挂号信息写入失败！");

        return responseResult;
    }


}
